package com.example.javamaday.leetcode;

import com.example.javamaday.leetcode.base.TreeNode;

import java.util.ArrayList;
import java.util.Stack;

public class LeetCodeTest0235 {


    public static void main(String[] args) {

    }


    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode currentNode = root;
        while (true) {
            if (isFather(currentNode.left, p, q) || isFather(currentNode.right, p, q)) {
                if (isFather(currentNode.left, p, q)) {
                    currentNode = currentNode.left;
                }
                if (isFather(currentNode.right, p, q)) {
                    currentNode = currentNode.right;
                }
            } else {
                break;
            }
        }
        return currentNode;
    }

    public boolean isFather(TreeNode root, TreeNode p, TreeNode q) {
        ArrayList<Integer> treeNumList = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode temp = stack.pop();
            if (temp != null) {
                treeNumList.add(temp.val);
                if (temp.right != null) {
                    stack.push(temp.right);
                }
                if (temp.left != null) {
                    stack.push(temp.left);
                }
            }
        }
        return treeNumList.contains(p.val) && treeNumList.contains(q.val);
    }

}
